﻿using System.ServiceModel;
using System.ServiceModel.Channels;
using CID.Domain.Infrastructure;
using CID.Execution.Support;
using CID.Execution.Support.Contracts;

namespace CID.Execution.Controller.Support
{
    class AgentServiceProxyFactory
    {
        public static readonly AgentServiceProxyFactory Instance = new AgentServiceProxyFactory();

        private ChannelFactory<IAgentService> channelFactory; 
        private AgentServiceProxyFactory()
        {
            channelFactory = new ChannelFactory<IAgentService>(new BasicHttpBinding());
        }

        public IAgentService Create(IDeploymentAgent deploymentAgent)
        {
            return channelFactory.CreateChannel(GetEndpointAddress(deploymentAgent));
        }

        public void Dispose(IAgentService agentServiceProxy)
        {
            if (agentServiceProxy is IChannel)
                (agentServiceProxy as IChannel).Close();
        }

        private static EndpointAddress GetEndpointAddress(IDeploymentAgent deploymentAgent)
        {
            return new EndpointAddress(UrlProvider.GetDeploymentAgentUrl(deploymentAgent.Address));
        }
    }
}
